package com.yh.correct.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.yh.common.utils.ExcelUtil;
import com.yh.correct.model.Condition;
import com.yh.correct.model.MonthTest;
import com.yh.correct.model.Page;
import com.yh.correct.model.ResultData;
import com.yh.correct.model.RewordPunish;
import com.yh.correct.service.IRewordPunishService;

/**
 * @author 刘文涛 E-mail: 894516860@qq.com
 * @version 创建时间：2017年3月10日 上午10:57:34 奖励惩罚记录模型控制器
 */
@RestController
@RequestMapping(value = "/rewordpunish")
public class RewordPunishController {
	/**
	 * 日志记录
	 */
	private static Logger logger = LogManager.getLogger(RewordPunishController.class);
	/**
	 * 注入奖励惩罚业务服务
	 */
	@Autowired
	private IRewordPunishService rewordpunishservice;

	/**
	 * 模糊查询 查询条件(矫正单位,服刑人员,奖惩日期,奖惩类别)
	 * 
	 * @return
	 */
	@RequestMapping(value = "/querylike")
	public Page queryLikeRuleBreak(int pageSize, int pageNum, Condition condition) {
		logger.info("查询条件" + condition);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pageSize", pageSize);
		map.put("pageNum", pageNum);
		map.put("cunit", condition.getCunit());
		map.put("cname", condition.getCname());
		map.put("cclazz", condition.getCclazz());
		try {
			if (condition.getCdate() != null && condition.getCdate() != "") {
				java.util.Date date = new SimpleDateFormat("yyyy-MM-dd").parse(condition.getCdate());
				java.sql.Date cdate = new java.sql.Date(date.getTime());
				map.put("cdate", cdate);
			}
		} catch (ParseException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		Page page = rewordpunishservice.getLikeRewordPunish(map);
		return page;
	}

	/**
	 * 获取奖惩记录详情
	 * 
	 * @param request
	 * @param rewordpunish
	 * @return
	 */
	@RequestMapping(value = "/detail")
	public ModelAndView getDetail(HttpServletRequest request, RewordPunish rewordpunish, String sort) {
		Map<String, Object> m = rewordpunishservice.getRewordPunishById(rewordpunish);
		Map<String, Object> rsMap = new HashMap<String, Object>();
		rsMap.put("details", m);
		logger.info("查看详情" + m.toString());
		if ("check".equals(sort)) {
			return new ModelAndView("examine/rewordpunish_check", rsMap);
		}
		return new ModelAndView("examine/rewordpunish_edit", rsMap);
	}

	/**
	 * 增加奖惩记录
	 * 
	 * @param rewordpunish
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/addRewordPunish")
	public ResultData addRewordPunish(RewordPunish rewordpunish, String adddate) throws ParseException {
		java.util.Date date1 = new SimpleDateFormat("yyyy-MM-dd").parse(adddate);
		java.sql.Date date = new java.sql.Date(date1.getTime());
		rewordpunish.setDate(date);
		logger.info("增加奖惩记录" + rewordpunish.toString());
		rewordpunishservice.addRewordPunish(rewordpunish);
		return new ResultData();
	}

	/**
	 * 删除奖惩记录
	 * 
	 * @param rewordpunish
	 * @return
	 */
	@RequestMapping(value = "/delRewordPunish")
	public ResultData delRewordPunish(RewordPunish rewordpunish) {
		logger.info("删除奖惩记录id=" + rewordpunish.getId());
		rewordpunishservice.delRewordPunish(rewordpunish);
		return new ResultData();
	}

	/**
	 * 修改奖惩记录
	 * 
	 * @param rewordpunish
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/updateRewordPunish")
	public ResultData updateRewordPunish(RewordPunish rewordpunish, String editdate) throws ParseException {
		java.util.Date date1 = new SimpleDateFormat("yyyy-MM-dd").parse(editdate);
		java.sql.Date date = new java.sql.Date(date1.getTime());
		rewordpunish.setDate(date);
		logger.info("修改奖惩记录id=" + rewordpunish.toString());
		rewordpunishservice.updateRewordPunish(rewordpunish);
		return new ResultData();
	}

	/**
	 * tree点击返回url
	 * 
	 * @return
	 */
	@RequestMapping("/url")
	public ModelAndView getUrl() {
		return new ModelAndView("examine/rewordpunish");
	}

	/**
	 * 根据奖励惩罚记录id批量删除
	 * 
	 * @param id
	 */
	@RequestMapping(value = "/getDeleteIds")
	public void getDeleteIds(int[] id) {
		RewordPunish rewordpunish = new RewordPunish();
		for (int i : id) {
			logger.info("批量删除奖励惩罚id=" + i);
			rewordpunish.setId(i);
			rewordpunishservice.delRewordPunish(rewordpunish);
		}
	}

	/**
	 * 导出Excel
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "exportExcel")
	public String download(int[] id, HttpServletRequest request, HttpServletResponse response) throws IOException {
		String fileName = "奖励惩罚记录excel文件";
		// 生成选择项的导出list
		List<Map<String, Object>> projects = new ArrayList<Map<String, Object>>();
		if (id != null) {
			RewordPunish rewordpunish = new RewordPunish();
			for (int i : id) {
				logger.info("批量导出奖励惩罚id=" + i);
				rewordpunish.setId(i);
				Map<String, Object> m = rewordpunishservice.getRewordPunishById(rewordpunish);
				projects.add(m);
			}
		} else {
			projects = createData();
		}
		// 填充projects数据
		List<Map<String, Object>> list = createExcelRecord(projects);
		String columnNames[] = { "序号", "矫正单位", "矫正人员", "奖惩日期", "奖惩类别", "奖惩内容", "状态", "备注" };// 列名
		String keys[] = { "id", "jname", "cname", "date", "clazz", "content", "status", "remark" };// map中的key
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		// 设置response参数，可以打开下载页面
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			// Simple read/write loop.
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (final IOException e) {
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
		return null;
	}

	private List<Map<String, Object>> createData() {
		// TODO Auto-generated method stub
		// List<Project> list=new ArrayList<Project>();
		List<Map<String, Object>> list = rewordpunishservice.getAllRewordPunish();
		return list;
	}

	private List<Map<String, Object>> createExcelRecord(List<Map<String, Object>> projects) {
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sheetName", "sheet1");
		listmap.add(map);
		Map<String, Object> object = null;
		for (int j = 0; j < projects.size(); j++) {
			object = projects.get(j);
			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("id", object.get("id"));
			mapValue.put("jname", object.get("jname"));
			mapValue.put("cname", object.get("cname"));
			mapValue.put("date", object.get("date"));
			mapValue.put("clazz", object.get("clazz"));
			mapValue.put("content", object.get("content"));
			mapValue.put("status", object.get("status"));
			mapValue.put("remark", object.get("remark"));
			listmap.add(mapValue);
		}
		return listmap;
	}
}
